package com.controller;

import com.entity.MaintenanceAreaLevel1;
import com.service.MaintenanceAreaLevel1Service;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/maintenance/area/level1")
public class MaintenanceAreaLevel1Controller {

    @Autowired
    private MaintenanceAreaLevel1Service maintenanceAreaLevel1Service;

    @PostMapping
    public MaintenanceAreaLevel1 create(@RequestBody MaintenanceAreaLevel1 maintenanceAreaLevel1) {
        return maintenanceAreaLevel1Service.save(maintenanceAreaLevel1);
    }

    @DeleteMapping("/{areaName}")
    public void delete(@PathVariable(value = "areaName") String areaName) {
        maintenanceAreaLevel1Service.deleteByAreaName(areaName);
    }

    @PutMapping("/{id}")
    public MaintenanceAreaLevel1 update(@PathVariable(value = "id") Integer id, @RequestBody MaintenanceAreaLevel1 maintenanceAreaLevel1) {
        maintenanceAreaLevel1.setId(id);
        return maintenanceAreaLevel1Service.save(maintenanceAreaLevel1);
    }

    @GetMapping("/page")
    public Page<MaintenanceAreaLevel1> page(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       @RequestParam(required = false) String areaName) {
        Page<MaintenanceAreaLevel1> page;
        if (areaName != null && !areaName.isEmpty()) {
            page = maintenanceAreaLevel1Service.findByAreaNameContaining(areaName, pageNum, pageSize);
        } else {
            page = maintenanceAreaLevel1Service.findAll(pageNum, pageSize);
        }
        return page;
    }
}